package com.weilf.zookeeper.lock;


import lombok.SneakyThrows;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 使用zookeeper 做分布式锁
 * @author weil-f
 * @date 2021/2/7 9:49
 */
public class ZkLockTest {

	private ZooKeeper zk ;

	@Before
	public void getZk(){
		try {
			zk = ZkUtils.instance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@After
	public void close(){
		try {
			zk.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void lockTest(){
		for (int i = 0; i < 10; i++) {
			new Thread(){
				@Override
				public void run() {
					LockWatcher watchCallBack = new LockWatcher();
					watchCallBack.setZk(zk);
					String threadName = Thread.currentThread().getName();
					watchCallBack.setThreadName(threadName);
					//每一个线程：
					//抢锁
					watchCallBack.tryLock();
					//干活
					System.out.println(threadName+" working...");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					//释放锁
					watchCallBack.unLock();


				}
			}.start();
		}

		while (true){

		}
	}
}
